package com.primaryedu.ui.fragment;

import java.io.File;

import org.json.JSONException;
import org.json.JSONObject;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ClearCacheRequest;
import com.android.volley.toolbox.DiskBasedCache;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.primaryedu.R;
import com.primaryedu.bean.AccountBean;
import com.primaryedu.data.Contants;
import com.primaryedu.data.GlobalData;
import com.primaryedu.ui.center.PersonalActivity;
import com.primaryedu.ui.center.SettingActivity;
import com.primaryedu.ui.repair.MyRepairActivity;
import com.primaryedu.widget.CircularImage;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.TextView;

/**
 * 我的
 *
 * @author jun.wang
 * @description
 * @data 2016年12月13日
 */
public class PersonalFragment extends Fragment implements OnClickListener {
    private final static int PERSONALPHOTO = 1; // "头像"返回的结果码
    private View view;
    protected RequestQueue requestQueue = null;
//    LoadImage loadImage;
    private CircularImage headImage;
    private TextView text_name;

    private Handler handler = new Handler() {
        public void handleMessage(android.os.Message msg) {

            switch (msg.what) {
                case 1001:
                    setData();
                    break;

                default:
                    break;
            }
        }

        ;
    };
    private TextView text_repair;
    private AccountBean bean;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_personal, container, false);
//		requestData();
        return view;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        init();
        requestData();
    }

    private void init() {
        ((TextView) view.findViewById(R.id.title)).setText("我的");
        view.findViewById(R.id.back).setVisibility(View.GONE);
        text_repair = (TextView) view.findViewById(R.id.text_repair);
        text_repair.setOnClickListener(this);
        view.findViewById(R.id.text_personal).setOnClickListener(this);
        view.findViewById(R.id.text_setting).setOnClickListener(this);
        headImage = (CircularImage) view.findViewById(R.id.headImage);
        text_name = (TextView) view.findViewById(R.id.text_name);

        requestQueue = Volley.newRequestQueue(getActivity());
       /* File cacheDir = new File(getActivity().getCacheDir(), "volley");
        DiskBasedCache cache = new DiskBasedCache(cacheDir);
        requestQueue.start();
        requestQueue.add(new ClearCacheRequest(cache, null));*/

//		loadImage = LoadImage.getInstance() ;

    }

    @Override
    public void onResume() {
        super.onResume();

//		requestData() ;
    }

    private void setData() {
//		headImage.setTag(bean.getData().getPhotourl());
//		loadImage.addTask(bean.getData().getPhotourl(), headImage);
//		loadImage.doTask();
        Glide.with(getActivity())
                .load(bean.getData().getPhotourl())
                .placeholder(R.drawable.head_nan)
                .error(R.drawable.head_nan)
                .centerCrop()
                .crossFade()
                .into(headImage);
        text_name.setText(bean.getData().getName());

        if (bean.getData().getUserType().contains("3")
                || bean.getData().getUserType().contains("4")) {
            text_repair.setVisibility(View.GONE);
        }
    }

    @Override
    public void onClick(View v) {
        Intent intent = null;

        switch (v.getId()) {
            case R.id.text_repair:
                intent = new Intent(getActivity(), MyRepairActivity.class);
                intent.putExtra("title", "我的办公");
                startActivity(intent);
                break;
            case R.id.text_personal:
                intent = new Intent(getActivity(), PersonalActivity.class);
//			 startActivity(intent);
                startActivityForResult(intent, PERSONALPHOTO);
                break;

            case R.id.text_setting:
                intent = new Intent(getActivity(), SettingActivity.class);
                startActivity(intent);
                break;

            default:
                break;
        }
    }

    private void requestData() {
        StringBuilder builder = new StringBuilder();
        builder.append(Contants.getAccount);
        builder.append("?userid=" + GlobalData.getUserId(getActivity()));

        StringRequest stringRequest = new StringRequest(Request.Method.GET,
                builder.toString(), new Response.Listener<String>() {

            @Override
            public void onResponse(String arg0) {

                try {
                    JSONObject json = new JSONObject(arg0);
                    String reason = json.getString("reason");
                    int result = json.getInt("result");
                    String data = json.getString("data");

                    if (result == 1) {

                        bean = new Gson().fromJson(arg0,
                                new TypeToken<AccountBean>() {
                                }.getType());
                        System.out.println("bean==" + bean);

                        GlobalData.accountBean = bean;
                        handler.sendEmptyMessage(1001);
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError arg0) {
//	            showToast(ErrorMsg.net_error) ;
            }
        });
        //为此get请求设置一个Tag属性
        stringRequest.setTag("GET_TAG");
        //将此get请求加入
        requestQueue.add(stringRequest);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // RESULT_OK，判断另外一个activity已经结束数据输入功能，Standard activity result:
        // operation succeeded. 默认值是-1
        if (resultCode == 3) {
            if (requestCode == PERSONALPHOTO) {
                requestData();
            }

        }
    }
}
